<?php


namespace apps\marriage\core\service;


use apps\marriage\core\logic\GoMessageLogic;
use apps\marriage\core\model\MemberRechargeRecord;
use apps\marriage\core\model\UserChatMessage;
use think\Exception;
use vm\com\BaseModel;
use vm\com\BaseService;

class UserChatMessageService extends BaseService
{

    /**
     * @return UserChatMessage
     */
    protected function getModel()
    {
        return new UserChatMessage();
    }

    /**
     * @return GoMessageLogic
     */
    private function getGoMessageLogic()
    {
        return logic('GoMessage', LOGIC_NAMESPACE);
    }

    /**
     * @return BaseService|UserService
     */
    private function getUserService()
    {
        return service('User', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|MemberProfileService
     */
    private function getMemberProfileService()
    {
        return service('MemberProfile', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|MemberRechargeRecordService
     */
    private function getMemberRechargeRecordService()
    {
        return service('MemberRechargeRecord', SERVICE_NAMESPACE);
    }

    public function count(array $params = [])
    {
        $model = $this->getModel();
        foreach ($params as $key => $val) {
            if(is_array($val)) {
                $model = $model->where($key, $val[0], $val[1]);
            } else if($key == 'min_send_time') {
                $model = $model->where('send_time', '>=', $val);
            } else if($key == 'max_send_time') {
                $model = $model->where('send_time', '<=', $val);
            } else {
                $model = $model->where($key, $val);
            }
        }
        return $model->count();
    }

    public function send($sendUid, $toUid, $msg, $needRealNameAuth = true)
    {
        $sendMember = $this->getMemberProfileService()->getByUserId($sendUid);
        if($needRealNameAuth && $sendMember['realname_auth_status'] == 0) {
            throw new Exception('请先完成实名认证');
        }

        $rights = $this->getMemberProfileService()->getVipRightsByUserId($sendUid);
        if($rights['send_msg_amount_per_day'] != -1
            && $this->count([
                'send_uid' => $sendUid,
                'min_send_time' => strtotime(date('Ymd') . ' 00:00:00'),
                'max_send_time' => strtotime(date('Ymd') . ' 23:59:59'),
            ]) >= $rights['send_msg_amount_per_day']) {
            throw new Exception('您当前每天可发'.$rights['send_msg_amount_per_day'].'条私信');
        }

        $data = [
            'send_uid' => $sendUid,
            'to_uid' => $toUid,
            'msg' => $msg,
            'status' => UserChatMessage::STATUS_WAIT_READ,
            'send_time' => time()
        ];
        $id = $this->create($data);
        $data['id'] = $id;

        if($this->getGoMessageLogic()->send($sendUid, $toUid, json_encode($data))) {
            return $data;
        } else {
            $this->deleteByPk($id);
            return false;
        }
    }

    public function getMyChatSessions($toUid)
    {
        $res = $this->getModel()->getMyChatSessions($toUid);
        $sessions = [];
        $userService = $this->getUserService();
        $memberProfileService = $this->getMemberProfileService();
        $memberRechargeRecordService = $this->getMemberRechargeRecordService();
        $receiverMemberRights = $memberProfileService->getVipRightsByUserId($toUid);
        foreach ($res as $rs) {
            $senderUser = $userService->getByPk($rs['send_uid']);
            $senderUser = arrayOnly($senderUser, ['id', 'nick', 'avatar_url']);
            $senderMember = $memberProfileService->getByUserId($rs['send_uid']);
            $senderMember = $memberProfileService->format($senderMember);
            $senderMemberRights = $memberProfileService->getVipRightsByUserId($rs['send_uid']);
            $lastSession = $this->getModel()->getLastChatSession($toUid, $rs['send_uid']);
            $lastSession['read'] = $lastSession['status'] == UserChatMessage::STATUS_WAIT_READ ? false : true;
            $unlock = false;
            if($senderMemberRights['send_msg_auto_unlock_for_receiver_enable']
                || $receiverMemberRights['receive_msg_auto_unlock_enable']) {   // 收信人有权免费查看，或发信人自动帮对方解锁
                $unlock = true;
            } else {
                if($memberRechargeRecordService->info([
                    'user_id' => $toUid,
                    'iid' => $rs['send_uid'],
                    'iid_type' => MemberRechargeRecord::IID_TYPE_UNLOCK_CHAT_SESSION
                ])) {
                    $unlock = true;
                } else {
                    if($rs['send_uid'] != $toUid) {
                        $lastSession['msg'] = '此条消息已隐藏,你与对方的聊天通道还没打开.';
                    }
                }
            }
            $sessions[] = [
                'sender' => [
                    'user' => $senderUser,
                    'member' => $senderMember
                ],
                'last_session' => $lastSession,
                'unlock' => $unlock
            ];
        }
        return $sessions;
    }

    public function getSession($toUid, $sendUid)
    {
        $memberProfileService = $this->getMemberProfileService();
        $receiverMemberRights = $memberProfileService->getVipRightsByUserId($toUid);
        $senderMemberRights = $memberProfileService->getVipRightsByUserId($sendUid);

        $unlock = false;
        if($senderMemberRights['send_msg_auto_unlock_for_receiver_enable']
            || $receiverMemberRights['receive_msg_auto_unlock_enable']) {   // 收信人有权免费查看，或发信人自动帮对方解锁
            $unlock = true;
        } else {
            if($this->getMemberRechargeRecordService()->info([
                'user_id' => $toUid,
                'iid' => $sendUid,
                'iid_type' => MemberRechargeRecord::IID_TYPE_UNLOCK_CHAT_SESSION
            ])) {
                $unlock = true;
            }
        }

        $res = $this->getModel()->getSession($toUid, $sendUid);
        $ids = [];
        if(!empty($res)) {
            foreach ($res as &$rs) {
                $ids[] = $rs['id'];
                if(!$unlock && $rs['send_uid'] == $sendUid) {
                    $rs['msg'] = '此条消息已隐藏,你与对方的聊天通道还没打开.';
                }
            }
            if($unlock) {
                $this->update([
                    'status' => UserChatMessage::STATUS_READ
                ], ['id' => $ids]);
            }
        }
        return $res;
    }
}